package org.ehe.erp.generate.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.erp.domain.finance.ErpFinancePayment;
import org.ehe.erp.generate.domain.GenerateNo;
import org.ehe.erp.generate.mapper.GenerateNoMapper;
import org.ehe.erp.generate.service.GenerateNoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author :zhangnn
 * @className :GenerateNoService
 * @description: TODO
 * @date 2025-09-05 13:34:02
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GenerateNoServiceImpl extends ServiceImpl<GenerateNoMapper, GenerateNo> implements GenerateNoService {

    /**
     * 生成支付编号
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public String generatePaymentNo(String prefix) {
        String dateStr = DateUtil.format(LocalDateTime.now(), "yyyyMMdd");
        prefix = prefix + dateStr;

        // 查询当天最大序号
        LambdaQueryWrapper<GenerateNo> wrapper = Wrappers.lambdaQuery();
        wrapper.like(GenerateNo::getPrefix, prefix);
        wrapper.orderByDesc(GenerateNo::getCode);
        wrapper.last("LIMIT 1");

        GenerateNo last = baseMapper.selectOne(wrapper);

        int sequence = 1;
        if (ObjectUtil.isNotNull(last) && StringUtils.isNotBlank(last.getCode())) {
            String lastNo = last.getCode();
            if (lastNo.length() >= prefix.length() + 3) {
                String sequenceStr = lastNo.substring(prefix.length());
                try {
                    sequence = Integer.parseInt(sequenceStr) + 1;
                } catch (NumberFormatException e) {
                    log.warn("解析付款单号序号失败: {}", lastNo);
                }
            }
        }
        //存入编号
        String code = prefix + String.format("%03d", sequence);
        GenerateNo generateNo = new GenerateNo();
        generateNo.setPrefix(prefix);
        generateNo.setCode(code);
        generateNo.setCreateBy(LoginHelper.getUsername());
        generateNo.setTenantId(LoginHelper.getTenantId());
        this.baseMapper.insert(generateNo);

        return prefix + String.format("%03d", sequence);
    }
}
